import React, { useState, useRef } from "react";
import { Track, Clip } from "../types";
import { Move } from "lucide-react";

const TRACK_HEIGHT = 100;
const PIXELS_PER_SECOND = 100;
const INITIAL_TRACKS: Track[] = [
  {
    id: 0,
    clips: [
      { id: "1", start: 0, duration: 5, track: 0, thumbnail: "https://images.unsplash.com/photo-1518806118471-f28b20a1d79d" },
      { id: "2", start: 7, duration: 3, track: 0, thumbnail: "https://images.unsplash.com/photo-1516035069371-29a1b244cc32" },
    ],
  },
  { id: 1, clips: [{ id: "3", start: 2, duration: 4, track: 1, thumbnail: "https://images.unsplash.com/photo-1464746133101-a2c3f88e0dd9" }] },
  { id: 2, clips: [] },
];
let START_LEFT = 0;

export function Timeline() {
  const [tracks, setTracks] = useState<Track[]>(INITIAL_TRACKS);
  // 当前正在拖拽的clip
  const [draggingClip, setDraggingClip] = useState<Clip | null>(null);
  // 当前控制元素大小的clip
  const [resizingClip, setResizingClip] = useState<{ clip: Clip; edge: "start" | "end" } | null>(null);
  const timelineRef = useRef<HTMLDivElement>(null);

  // 开始拖拽
  const handleDragStart = (clip: Clip, e: React.DragEvent) => {
    // 拖拽点离边界的位置
    START_LEFT = e.nativeEvent.layerX;
    setDraggingClip(clip);
  };

  const handleDragEnd = (e: React.DragEvent) => {
    setDraggingClip(null);
    e.stopPropagation();
  }

  // 拖拽过程中
  const handleDragOver = (e: React.DragEvent) => {
    e.stopPropagation();
    e.preventDefault();
    if (!draggingClip || !timelineRef.current || resizingClip) return;

    const rect = timelineRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left - START_LEFT;
    const y = e.clientY - rect.top;

    const trackIndex = Math.floor(y / TRACK_HEIGHT);
    const newStart = Math.max(0, Math.round(x / PIXELS_PER_SECOND));

    if (trackIndex >= tracks.length) {
      setTracks((prev) => [...prev, { id: tracks.length, clips: [] }]);
    }

    setTracks((prev) => {
      const newTracks = prev.map((track) => ({
        ...track,
        clips: track.clips.filter((c) => c.id !== draggingClip.id),
      }));

      const targetTrack = newTracks[Math.min(trackIndex, tracks.length - 1)];
      targetTrack.clips.push({
        ...draggingClip,
        start: newStart,
        track: targetTrack.id,
      });

      return newTracks;
    });
  };

  const handleResizeStart = (clip: Clip, edge: "start" | "end", e: React.MouseEvent) => {
    setResizingClip({ clip, edge });
    e.stopPropagation();
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    e.stopPropagation();
    e.preventDefault();
    if (!resizingClip || !timelineRef.current) return;

    const rect = timelineRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const newTime = Math.max(0, Math.round(x / PIXELS_PER_SECOND));

    setTracks((prev) =>
      prev.map((track) => ({
        ...track,
        clips: track.clips.map((clip) => {
          if (clip.id !== resizingClip.clip.id) return clip;

          if (resizingClip.edge === "start") {
            const newStart = Math.min(newTime, clip.start + clip.duration - 1);
            return {
              ...clip,
              start: newStart,
              duration: clip.start + clip.duration - newStart,
            };
          } else {
            const newDuration = Math.max(1, newTime - clip.start);
            return { ...clip, duration: newDuration };
          }
        }),
      }))
    );
  };

  const handleMouseUp = () => {
    setResizingClip(null);
    setDraggingClip(null);
    START_LEFT = 0;
  };

  return (
    <div className='bg-gray-900 p-4 w-full overflow-x-auto'>
      <div
        ref={timelineRef}
        className='relative'
        style={{ height: tracks.length * TRACK_HEIGHT }}
        onDragOver={handleDragOver}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseUp}
      >
        {tracks.map((track, i) => (
          <div
            key={track.id}
            className='absolute w-full border-b border-gray-700'
            style={{
              top: i * TRACK_HEIGHT,
              height: TRACK_HEIGHT,
            }}
          >
            {track.clips.map((clip) => (
              <div
                key={clip.id}
                draggable
                className='absolute top-2 bottom-2 bg-gray-800 rounded-lg overflow-hidden cursor-move flex items-center group'
                style={{
                  left: clip.start * PIXELS_PER_SECOND,
                  width: clip.duration * PIXELS_PER_SECOND,
                }}
                onDrag={handleMouseMove}
                onDragStart={(e) => handleDragStart(clip, e)}
                onDragEnd={e => handleDragEnd(e)}
              >
                <img
                  src={clip.thumbnail}
                  alt=''
                  className='h-full w-full object-cover opacity-50'
                />
                <div
                  className='absolute left-0 top-0 bottom-0 w-4 cursor-ew-resize hover:bg-blue-500/50'
                  onMouseDown={(e) => handleResizeStart(clip, "start", e)}
                />
                <div
                  className='absolute right-0 top-0 bottom-0 w-4 cursor-ew-resize hover:bg-blue-500/50'
                  onMouseDown={(e) => handleResizeStart(clip, "end", e)}
                />
                <Move className='absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100' />
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}
